package cn.javadog.smartbreeding.record.service.impl;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

import cn.javadog.smartbreeding.core.service.AuthService;
import cn.javadog.smartbreeding.record.entity.Role;
import cn.javadog.smartbreeding.record.entity.User;
import cn.javadog.smartbreeding.core.config.exception.UserAuthException;
import cn.javadog.smartbreeding.record.mapper.RoleMapper;
import cn.javadog.smartbreeding.record.mapper.UserMapper;
import cn.javadog.smartbreeding.record.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

/**
 * @author 余勇
 */
@Service
@com.alibaba.dubbo.config.annotation.Service
public class AuthServiceImpl implements AuthService {

	@Autowired
	private UserMapper userMapper;
	@Autowired
	private RoleMapper roleMapper;

	@Override
	public String login(String username, String password) {
		User user = userMapper.selectOne(Wrappers
			.<User>lambdaQuery()
			.eq(User::getUsername,username)
			.eq(User::getPassword,password));

		if (Objects.isNull(user) || !user.getPassword().equals(password)) {
			throw new UserAuthException();
		}

		List<Role> roles = Collections.singletonList(roleMapper.selectById(user.getId()));
		return JwtUtil.generateToken(username, roles);
	}
}
